package com.example.myys.viewModel.yyModel

import android.media.AudioAttributes
import android.media.MediaPlayer
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myys.MyApplication
import com.example.myys.data.entity.DataBean
import com.example.myys.data.repository.MusicRepository
import com.example.myys.ui.Resource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.io.IOException

class YyViewModel:ViewModel() {
    val musicRepository=MusicRepository()
    
    private var mData: MutableList<DataBean> = ArrayList()

    //推荐
    private val _scTjState: MutableStateFlow<Resource<List<DataBean>>>
            = MutableStateFlow(value = Resource.Error())

    val scTjState: StateFlow<Resource<List<DataBean>>>
        get() = _scTjState
    //收藏
    private val _sjState: MutableStateFlow<Resource<List<DataBean>>>
            = MutableStateFlow(value = Resource.Loading())

    val sjState: StateFlow<Resource<List<DataBean>>>
        get() = _sjState

    fun getXsWbDate() {
        viewModelScope.launch(Dispatchers.IO){
            val musicList= musicRepository.getMusicRecommend()
            if (musicList == null) {
                _scTjState.value= Resource.Error()
            }else{
                _scTjState.value= Resource.Success(musicList)
            }
        }
    }
    fun getSearchMusic(keyword:String) {
        _scTjState.value= Resource.Loading()
        viewModelScope.launch(Dispatchers.IO){
            val musicList= musicRepository.getMusicByKeyword(keyword)
            if (musicList == null) {
                _scTjState.value= Resource.Error()
            }else{
                _scTjState.value= Resource.Success(musicList)
            }
        }
    }
    fun getMusicShelf(){
        _sjState.value= Resource.Loading()
        viewModelScope.launch(Dispatchers.IO) {
            val sjList= musicRepository.getMusicShelf()
            if(sjList==null){
                _sjState.value= Resource.Error()
            }else{
                _sjState.value= Resource.Success(sjList)
            }

        }
    }
    fun addMusicShelf(DataBean: DataBean){
        viewModelScope.launch(Dispatchers.IO) {
            musicRepository.addMusicShelf(DataBean)
            getMusicShelf()
        }
    }

    //记录当前正在播放的音乐的位置
    private var currentPlayPosition = -1

    //记录暂停音乐时进度条的位置
    private var currentPausePositionInSong = 0

    //创建MediaPlayer对象
    private var mediaPlayer: MediaPlayer = MediaPlayer()

    //判断是不是首次启动 默认值为false
    private var isFirstRun = false

    private val _isPlaying = MutableLiveData<Boolean>()
    val isPlaying: LiveData<Boolean> = _isPlaying

    private val _localMusicBean =
        MutableLiveData(DataBean())

    val localMusicBean: LiveData<DataBean>
        get() = _localMusicBean


    fun playLastMusic(){
        if(currentPlayPosition==0||currentPlayPosition==-1){
            Toast.makeText(MyApplication.instance,"已经是第一首了，没有上一曲！",Toast.LENGTH_SHORT).show()
        }else{
            //获取上一首歌曲
            val lastMusicBean = mData[currentPlayPosition-1]
            currentPlayPosition-=1
            playMusicInMusicBean(lastMusicBean)
        }
    }

    fun playCurrentMusic(){
        if (currentPlayPosition == -1) {
            Toast.makeText(MyApplication.instance,"请选择想要播放的音乐",Toast.LENGTH_SHORT).show()
        } else {
            if (mediaPlayer.isPlaying) {
                //此时处于播放状态，需要暂停音乐
                pauseMusic()
            } else {
                //此时没有播放音乐，点击开始播放音乐
                playMusic()
            }
        }
    }

    fun playNextMusic(){
        if(currentPlayPosition==mData.size-1||currentPlayPosition==mData.size){
            Toast.makeText(MyApplication.instance,"已经是最后一首了，没有下一曲！",Toast.LENGTH_SHORT).show()
        }else{
            //获取上一首歌曲
            val nextMusicBean = mData[currentPlayPosition+1]
            currentPlayPosition+=1
            playMusicInMusicBean(nextMusicBean)
        }
    }

    fun playMusicInMusicBean(musicBean: DataBean) {
        /*根据传入对象播放音乐*/
        //设置底部显示的歌手名称和歌曲名
        stopMusic()
        //重置多媒体播放器
        mediaPlayer.reset()
        //设置新的播放路径
        try {
            viewModelScope.launch(Dispatchers.IO) {
                if (!musicBean.url.startsWith("http")) {
                    val playerUrl =
                        musicRepository.getMusicPlayUrl(musicBean.url + "#" + musicBean.cover)
                            ?.split("#")
                    if (playerUrl != null) {
                        musicBean.url = playerUrl.get(0)
                        musicBean.cover = playerUrl.get(1)
                    }
                }
                mediaPlayer.apply {
                    setAudioAttributes(
                        AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                            .setUsage(AudioAttributes.USAGE_MEDIA)
                            .build()
                    )
                    musicBean.url.let {
                        setDataSource(it)
                    }
                }
                playMusic()
                onMusicChanged(musicBean)
                mData.add(musicBean)
                currentPlayPosition = mData.size - 1
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun playMusic() {
        //播放音乐的函数
        if (!mediaPlayer.isPlaying) {
            if (currentPausePositionInSong == 0) {
                try {
                    mediaPlayer.prepare()
                    mediaPlayer.start()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            } else {
                //从暂停到播放
                mediaPlayer.seekTo(currentPausePositionInSong)
                mediaPlayer.start()
            }
            _isPlaying.postValue(true)
        }
    }

    private fun pauseMusic() {
        /* 暂停音乐的函数*/
        if (mediaPlayer.isPlaying) {
            currentPausePositionInSong = mediaPlayer.currentPosition
            mediaPlayer.pause()
            _isPlaying.postValue(false)
        }
    }

    fun stopMusic() {
        if (isFirstRun) {
            Log.d("MainActivity", "stopMusic()")
            currentPausePositionInSong = 0
            mediaPlayer.pause()
            mediaPlayer.seekTo(0)
            mediaPlayer.stop()
        } else {
            isFirstRun = true
        }
    }

    private fun onMusicChanged(localMusicBean: DataBean) {
        _localMusicBean.postValue(localMusicBean)
    }

    init {
        getXsWbDate()
        getMusicShelf()
    }
}